package com.tanhua.admin.service;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tan.model.domain.Analysis;
import com.tanhua.admin.mapper.AnalysisMapper;
import com.tanhua.admin.mapper.LogMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class AnalysisService {
    @Autowired
    private AnalysisMapper analysisMapper;
    @Autowired
    private LogMapper logMapper;
    //定时统计tb_log表数据，保存并更新analysis表数据
    /*
    * 1. 查询tb_log表数据，统计分析数据(1.注册量，2.活跃量，3.留存量)
    * 2.构造Analysis对象，调用mapper保存到数据库中
    *
    * */



    public void analysis() throws ParseException {
        // 定义查询日期
        String recordDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String yesterday = DateUtil.yesterday().toString("yyyy-MM-dd");

        // 统计注册数量
        Integer numRegistered = logMapper.queryByTypeAndLogTime("0102", recordDate);
        // 统计活跃数量
        Integer numActive = logMapper.queryByLogTime(recordDate);
        // 统计留存数量
        Integer numRetention1d = logMapper.queryNumRetention1d(recordDate, yesterday);
        // 统计登录数量
        Integer numLogin = logMapper.queryByTypeAndLogTime("0101", recordDate);

        // 构造日期查询数据
        QueryWrapper<Analysis> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("record_date", recordDate);
        Analysis analysis = analysisMapper.selectOne(queryWrapper);

        // 如果存在，更新，不存在，保存
        if (analysis != null) {
            analysis.setNumRegistered(numRegistered);
            analysis.setNumActive(numActive);
            analysis.setNumLogin(numLogin);
            analysis.setNumRetention1d(numRetention1d);
            analysisMapper.updateById(analysis);
            System.out.println("更新成功");
        } else {
            analysis = new Analysis();
            Date date = DateUtil.parse(recordDate); // 使用Hutool的DateUtil进行解析
            analysis.setRecordDate(date);
            analysis.setCreated(date);
            analysis.setNumRegistered(numRegistered);
            analysis.setNumActive(numActive);
            analysis.setNumLogin(numLogin);
            analysis.setNumRetention1d(numRetention1d);
            analysisMapper.insert(analysis);
            System.out.println("保存成功");
        }

    }
}
